<template>
  <div class="groupManage-page app-container">
    <div class="container">
      <div class="container-header">
        <div class="left">
          <div class="title">策略组合</div>
          <el-form ref="dataForm" :inline="true" label-width="80px" :model="dataForm">
            <el-form-item label="" prop="compositionName">
              <el-input v-model="dataForm.compositionName" size="small" clearable @keyup.enter.native="searchList" placeholder="请输入组合名称" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item label="" label-width="60px" prop="mark">
              <el-input v-model="dataForm.mark" size="small" clearable @keyup.enter.native="searchList" placeholder="请输入备注" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px">
              <el-button class="bg-green" size="small" @click="searchList">查询</el-button>
              <el-button size="small" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-button v-if="!isOpen" type="danger" size="small" @click="addOrUpdateHandle()">添加</el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        stripe
        fit
        size="mini"
        row-key="compositionId"
        @sort-change="sortCchange"
        lazy
        :header-cell-style="{color:'#333'}"
        style="width: 100%;"
      >
        <!-- :load="loadChildTable" -->
        <!-- :tree-props="{children: 'children', hasChildren: 'hasClassify'}" -->
        <el-table-column type="compositionId" prop="compositionId" label="编号" align="center" width="80" fixed sortable="custom">
          <template slot-scope="{row}">{{row.compositionId}}</template>
        </el-table-column>
        <el-table-column prop="compositionName" label="组合名称" min-width="160" fixed show-overflow-tooltip sortable="custom">
          <template slot-scope="{row, $index}">
            <span
              v-if="row.hasNetWorth && !row.classifyId"
              @click="loadChildTable(row, $index)"
            >
              <svg v-show="row.treeHas" class="icon svg-icon" aria-hidden="true">
                <use xlink:href="#icon-a-Icon-shouqi"></use>
              </svg>
              <svg v-show="!row.treeHas" class="icon svg-icon" aria-hidden="true">
                <use xlink:href="#icon-Icon-zhankai"></use>
              </svg>
            </span>
            <!-- 多开标签 -->
            <router-link v-if="row.hasNetWorth&&(!row.classifyId)" style="cursor: pointer;color: #1890ff;" :to="'/strategyComb/combManage/netWorthAnalysis/'+row.compositionId">{{ row.compositionName }}</router-link>
            <span v-else-if="row.hasNetWorth" style="margin-left: 40px;cursor: pointer;color: #1890ff;" @click.stop="classifyDeltailHandle(row.classifyId)">{{ row.classfyName }}</span>
            <span v-else style="cursor: pointer;color: #666;" @click.stop="$message('该组合净值不存在，无法查看详情')">{{ row.compositionName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="对比" align="center" fixed>
          <template slot-scope="{row, $index}">
            <span v-if="row.hasNetWorth&&(!row.classifyId)" class="pointer" :class="{'fontcolor': !row.addContrast}" @click="addContrasthandle(row, $index)">
              <span v-show="!row.addContrast" class="iconfont icon-jia" />
              <span v-show="row.addContrast" class="iconfont icon-check contrastGray" />
              <span :class="{'contrastGray': row.addContrast}" style="padding-left: 2px;">{{!row.addContrast ? '对比' : '已加'}}</span>
            </span>
            <span v-else-if="row.hasNetWorth"></span>
            <span v-else class="contrastGray" @click.stop="$message('该组合净值不存在，不能对比')">
              <span class="iconfont icon-jia" />
              <span style="padding-left: 2px;">对比</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="initMoney" label="投资金额(万元)" width="140" align="center" sortable="custom">
          <template slot-scope="{row}">
            <el-tooltip effect="dark" :content="`已占用金额：${row.occupiedMoney||'/'}`" placement="top">
              <span>{{row.initMoney}}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="sinceCreatedIncomRate" label="收益率" min-width="100" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceCreatedIncomRate" 
            :class="row.sinceCreatedIncomRate>=0?'positiveFc':'negativeFc'">{{ row.sinceCreatedIncomRate }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="sinceOneYearIncomRate" label="近1年收益率" min-width="130" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceOneYearIncomRate" 
            :class="row.sinceOneYearIncomRate>=0?'positiveFc':'negativeFc'">{{ row.sinceOneYearIncomRate }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="sinceCreatedVolatility" label="波动率" min-width="100" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceCreatedVolatility">{{ row.sinceCreatedVolatility }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="sinceOneYearVolatility" label="近1年波动率" min-width="130" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceOneYearVolatility">{{ row.sinceOneYearVolatility }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="sinceCreatedSharpeRate" label="夏普率" min-width="100" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceCreatedSharpeRate">{{ row.sinceCreatedSharpeRate }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="sinceOneYearSharpeRate" label="近1年夏普率" min-width="130" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceOneYearSharpeRate">{{ row.sinceOneYearSharpeRate }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="sinceCreatedMaxPullBack" label="最大回撤" min-width="100" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceCreatedMaxPullBack">{{ row.sinceCreatedMaxPullBack }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="sinceOneYearMaxPullBack" label="近1年最大回撤" min-width="140" show-overflow-tooltip align="center" sortable="custom">
          <template slot-scope="{row}">
            <span v-if="row.sinceOneYearMaxPullBack">{{ row.sinceOneYearMaxPullBack }}%</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdName" label="创建人" width="110" align="center"></el-table-column>
        <el-table-column prop="createdTime" label="创建日期" width="100" align="center" sortable="custom">
          <template slot-scope="{row}">
            <span>{{ row.createdTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="!isOpen" label="操作" width="240" fixed="right">
          <template slot-scope="{row}">
            <el-button v-if="!row.classifyId" class="filter-item" size="mini" icon="el-icon-coin" @click="configHandle(row.compositionId)">
              配置组合
            </el-button>
            <el-button class="filter-item" size="mini" icon="el-icon-connection" @click="goDownStrategyHandle(row)">
              下属策略
            </el-button>
            <el-popover
              v-if="!row.classifyId"
              popper-class="policyManage_popover"
              trigger="hover"
              placement="bottom"
            >
              <div class="flex-vh-center">
                <el-button v-if="!row.classifyId" class="filter-item" size="mini" style="margin-bottom: 10px;" icon="el-icon-copy-document" @click="copyHandle(row.compositionId)">
                  复制
                </el-button>
                <!-- <el-button class="filter-item" size="mini" type="primary" icon="el-icon-connection" @click="goCombManageHandle(row)">
                  下属分类
                </el-button> -->
                <el-button v-if="!row.classifyId" class="filter-item" size="mini" style="margin-left: 0px;" icon="el-icon-delete" @click="deleteHandle(row)">
                  删除
                </el-button>
              </div>
              <span class="operationMore" slot="reference">···</span>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageCurrent" :limit.sync="listQuery.limit" @pagination="getList" />

      <addOrUpdateOpen v-if="addOrUpdateView" ref="addOrUpdateOpen" :userId="userId" @closeOpen="getList"></addOrUpdateOpen>
      <globalContrastOpen ref="globalContrastOpen" :list="contrastList"></globalContrastOpen>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import { findStrategyCompositionByPage, deleteStrategyCompositionById, copyStrategyComposition } from '@/api/combManage'
import globalContrastOpen from '@/components/investComn/globalContrastOpen.vue'
import { findStrategyClassifyByPage } from '@/api/groupManage'
import addOrUpdateOpen from './addOrUpdateOpen.vue'
import { rmoney } from '@/utils'

export default {
  name: 'Combination',
  components: { addOrUpdateOpen, Pagination, globalContrastOpen },
  props: {
    isOpen: {
      type: Boolean,
      defaultL: false
    }
  },
  data() {
    return {
      tableKey: 1,
      addContrasting: false, // 是否有勾选全局对比

      addOrUpdateView: false,
      listLoading: false,
      dataForm: {},
      total: 0,
      list: [],
      listQuery: {
        pageCurrent: 1,
        limit: 20
      },
      rmoney: Function,
      orderInfo: {}
    }
  },
  computed: {
    ...mapGetters(['userId', 'contrastList'])
  },
  watch: {
    contrastList(newList, oldList) {
      if(newList.length == oldList.length) { // todo 此处newList==oldList则是数组减少，未知原因
        this.syncContrastListHandle()
      }
      if(!newList.length) {
        this.list.forEach((row, i) => {
          row.addContrast = false
          this.$set(this.list, i, row)
        })
        // this.tableKey++
      }
    }
  },
  created() {
    this.rmoney = rmoney
    this.getList()
  },
  activated() {
    if(this.contrastList.length) {
      this.$refs.globalContrastOpen.showOpen = true
    }
    this.getList()
  },
  methods: {
    sortCchange(column) {
      if (!column.order) {
        this.orderInfo = {};
      } else {
        this.orderInfo = {
          [column.prop]:
            column.order == "ascending" ? "asc" : "desc"
        };
      }
      this.getList();
    },
    // 同步对比框数据和列表数据
    syncContrastListHandle() {
      if(!this.contrastList.length) {
        this.list.forEach((row, i) => {
          row.addContrast = false
          this.$set(this.list, i, row)
        })
      }else {
        const list = this.contrastList.filter(item => item.contrastObj.type==3)
        this.list.forEach((row, index) => {
          row.addContrast = false
          this.$set(this.list, index, row)
          const i = list.findIndex(item => item.contrastObj.id==row.compositionId)
          if(i!=-1) {
            this.list[index].addContrast = true
          }
        })
      }
    },
    addContrasthandle(row, i) {
      this.$refs.globalContrastOpen.showOpen = true
      this.$store.commit('contrast/toggleShowOpen', true)
      row.addContrast = !row.addContrast
      if(this.contrastList.length==20) {
        this.$message({
          message: '最多添加20条数据',
          type: 'warning'
        })
        return
      }
      this.$set(this.list, i, row)  // 更新表格数据
      if(row.addContrast) {
        row.contrastObj = {
          type: 3,
          id: row.compositionId,
          name: row.compositionName,
          annualizedIncome: row.sinceOneYearIncomRate,
          annualFluctuations: row.sinceOneYearVolatility
        }
        this.$store.commit('contrast/addContrastList', row)
      }else {
        const i = this.contrastList.findIndex(item => item.contrastObj.id==row.compositionId&&item.contrastObj.type==3)
        this.$store.commit('contrast/removeContrastList', i)
      }
    },
    loadChildTable(row, index) {
      if (row.treeHas) {
        this.list = this.list.filter((item) => {
          if (item.compositionName === row.compositionName && item.classifyId) {
            return false
          }
          return item
        })
        row.treeHas = false
        return
      }
      findStrategyClassifyByPage({
        compositionId: row.compositionId,
        compositionName: row.compositionName,
        userId: this.userId,
        pageCurrent: 1,
        limit: 1000
      }).then(res => {
        row.treeHas = true
        res.body.list.map((item) => {
          item.old_compositionId = item.compositionId
          item.compositionId = 'F' + item.classifyId
        })
        const i = index + 1
        this.list.splice(i, 0, ...res.body.list)
      })
    },
    goDownStrategyHandle(row) {
      if(row.classifyId) {
        this.$router.push({
          path: '/strategyComb/strategyList',
          query: {
            classifyId: row.classifyId,
            classifyName: row.classfyName,
            compositionId: row.old_compositionId,
            compositionName: row.compositionName,
          }
        })
      }else {
        this.$router.push({
          path: '/strategyComb/strategyList',
          query: {
            compositionId: row.compositionId,
            compositionName: row.compositionName,
          }
        })
      }
    },
    copyHandle(compositionId) {
      copyStrategyComposition({
        compositionId
      }).then(res => {
        if(res.code == 0) {
          this.$notify({
            message: res.body, 
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      })
    },
    configHandle(compositionId) {
      this.$router.push({
        path: '/strategyComb/combManage/config',
        query: {
          compositionId
        }
      })
    },
    goCombManageHandle(row) {
      this.$router.push({
        path: '/strategyComb/groupManage',
        query: {
          compositionId:　row.compositionId,
          compositionName:　row.compositionName,
        }
      })
    },
    selctInvestNameHandle(strategyInfoVo) {
      this.dataForm.strategyId = strategyInfoVo.strategyId
      this.dataForm.strategyName = strategyInfoVo.strategyName
    },
    groupDeltailHandle(id) {
      this.$router.push({
        path: '/strategyComb/combManage/netWorthAnalysis',
        query: {
          id
        }
      })
    },
    classifyDeltailHandle(id) {
      this.$router.push({
        path: `/strategyComb/groupManage/netWorthAnalysis/${id}`
      })
    },
    submitHandle(row) {
      this.$emit('selctCombination', { compositionId: row.compositionId, compositionName: row.compositionName })
    },
    addOrUpdateHandle(row) {
      this.$router.push({
        path: '/strategyComb/combManage/config',
        query: {
          type: 'created',
        }
      })
    },
    deleteHandle(row) {
      this.$confirm(`确认删除组合名称【${row.compositionName}】此条数据？`, '提示', {
        type: 'warning'
      }).then(_ => {
        deleteStrategyCompositionById({
          compositionId: row.compositionId
        }).then(res => {
          if(res.code == 0) {
            this.$notify({
              message: res.msg, 
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      }).catch(_ => {})
    },
    resetForm() {
      this.$refs.dataForm.resetFields()
      this.getList()
    },
    searchList() {
      this.listQuery.pageCurrent = 1
      this.getList()
    },
    getList() {
      this.listLoading = true
      findStrategyCompositionByPage({
        ...this.dataForm,
        ...this.listQuery,
        orderInfo: this.orderInfo,
        userId: this.userId
      }).then(res => {
        this.listLoading = false
        this.list = res.body.list
        this.total = res.body.total

        if(this.contrastList.length) this.syncContrastListHandle()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.groupManage-page {
  position: relative;
  .icon-jia {
    font-size: 12px;
  }
}
.svg-icon{
  width: 18px;
  height:18px;
  margin-right: 5px;
  font-size: 18px;
  vertical-align: -0.18em;
  cursor: pointer;
}
.operationMore {
  padding-left: 10px;
  font-weight: bold;
  cursor: pointer;
}
</style>

